<template>
  <div v-loading="loading" class="organization-main clearfix">
    <!--tree start-->
    <div class="tree-container fr">
      <el-scrollbar style="height:100%" class="app-hid-scrollbar-x">
        <el-tree
          ref="treeList"
          :data="treeList"
          node-key="id"
          default-expand-all
          highlight-current
          :expand-on-click-node="false"
          class="tree-content"
          :current-node-key="activeTree?activeTree.id:null"
          @node-click="handleTreeClick"
        >
          <div slot-scope="{ node, data }" class="custom-tree-node flex-x-between-center">
            <div><i class="el-icon-office-building app-color-primary" />&nbsp;&nbsp;{{ data.name }}</div>
            <el-dropdown v-if="$isAuthBtn(['SP_BTN_ORG_ADD','SP_BTN_ORG_MODIFY','SP_BTN_ORG_DELETE'])" :hide-on-click="false" class="dropdown">
              <!--<span v-if="$isAuthBtn(['SP_BTN_ORG_ADD','SP_BTN_ORG_MODIFY','SP_BTN_ORG_DELETE'])" class="el-dropdown-link">-->
              <span class="el-dropdown-link">
                <i class="el-icon-more" />
              </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item v-if="$isAuthBtn(['SP_BTN_ORG_ADD'])" @click.native="handleEditOrg('add',node,data)">
                  新增组织
                </el-dropdown-item>
                <el-dropdown-item v-if="node.level!==1&&$isAuthBtn(['SP_BTN_ORG_MODIFY'])" @click.native="handleEditOrg('edit',node,data)">
                  编辑组织
                </el-dropdown-item>
                <el-dropdown-item v-if="node.level!==1&&$isAuthBtn(['SP_BTN_ORG_DELETE'])" @click.native="handleDelOrg(node, data)">
                  删除组织
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </div>
        </el-tree>
      </el-scrollbar>
    </div>
    <!--tree end-->

    <!--list start-->
    <div class="table-container">
      <div class="table-title flex-x-between-center">
        <div>当前部门：<span class="org-name">{{ activeTree ? activeTree.name : '所有部门' }}</span></div>
        <div>
          <el-button v-if="$isAuthBtn(['SP_BTN_ORG_ADD'])" type="primary" size="small" round class="btn-tree" @click="handleEditOrg('add')">
            新增组织架构
          </el-button>
          <el-button v-if="$isAuthBtn(['SP_BTN_USER_ADD'])" type="primary" size="small" round @click="handleEditUser('add')">
            新增成员
          </el-button>
          <!--          <el-button type="primary" size="small" round>微信邀请</el-button>-->
        </div>
      </div>

      <!--筛选条件-->
      <el-form ref="listFilterForm" :inline="true" :model="listFilterForm" label-width="100px" size="small">
        <el-form-item
          prop="name"
          label="姓名："
        >
          <el-input
            v-model="listFilterForm.name"
            placeholder="请输入"
            clearable
            class="app-w-350"
            @keyup.enter.native="submitListFilterForm"
          />
        </el-form-item>
        <div>
          <el-form-item label=" ">
            <el-button type="primary" round @click="submitListFilterForm">查询成员</el-button>
            <el-button round @click="resetListFilterForm">重置条件</el-button>
          </el-form-item>
        </div>
      </el-form>

      <!--列表-->
      <el-table :data="list" border stripe size="small" style="width: 100%">
        <el-table-column label="序号" type="index" align="center" width="60">
          <template slot-scope="scope">
            <span>{{ (paginationConfig.page - 1) * paginationConfig.pageSize + scope.$index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="姓名" />
        <el-table-column prop="username" label="登录名" />
        <el-table-column prop="mobilePhone" label="手机" />
        <el-table-column prop="orgList" label="部门">
          <template slot-scope="scope">
            <span v-if="!scope.row.orgList||scope.row.orgList===0">-</span>
            <el-tag v-for="item in scope.row.orgList" :key="item.orgId" style="margin:3px" size="small">
              {{ item.orgName }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="roles" label="角色">
          <template slot-scope="scope">
            <span v-if="!scope.row.roles||scope.row.roles.length===0">-</span>
            <el-tag v-for="item in scope.row.roles" :key="item.id" style="margin:3px" size="small">{{ item.name }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="wechat" label="微信">
          <template slot-scope="scope">
            <span v-if="scope.row.wechat">{{ scope.row.wechat.nickname }}</span>
            <span v-else>未绑定</span>
          </template>
        </el-table-column>
        <!--<el-table-column prop="status" label="状态">-->
        <!--  <template slot-scope="scope">-->
        <!--    <el-tag v-if="scope.row.status===1">启用中</el-tag>-->
        <!--    <el-tag v-else type="danger">已停用</el-tag>-->
        <!--  </template>-->
        <!--</el-table-column>-->
        <el-table-column label="操作" width="220">
          <template slot-scope="scope">
            <el-button v-if="$isAuthBtn(['SP_BTN_USER_MODIFY'])" type="text" size="mini" round @click="handleEditUser('edit',scope.row)">
              编辑
            </el-button>
            <el-button v-if="$isAuthBtn(['SP_BTN_USER_MODIFY'])" type="text" size="mini" round @click="handleEditUserPsw(scope.row)">
              重置密码
            </el-button>
            <el-popover
              v-model="scope.row.isShowBindWechatPopover"
              placement="right"
              width="300"
              trigger="click"
              @hide="bindWechatPopoverHide"
            >
              <div v-loading="bindWechatCodeLoading" class="wx-qrcode-popover flex-y-center-center">
                <div class="wx-qrcode-content flex-y-center-center">
                  <div class="qr-code">
                    <el-image v-if="bindWechatQrCodeUrl" :src="bindWechatQrCodeUrl" />
                  </div>
                  <div style="font-size: 12px;text-align: center;margin-top: 10px">微信扫一扫绑定账号：{{
                    scope.row.username
                  }}
                  </div>
                </div>
              </div>
              <el-button
                v-if="!scope.row.wechat&&$isAuthBtn(['SP_BTN_USER_MODIFY'])"
                slot="reference"
                type="text"
                size="mini"
                style="margin:0 10px"
                round
                @click="handleBindUserWechat(scope.row)"
              >绑定微信
              </el-button>
            </el-popover>
            <el-button
              v-if="scope.row.wechat&&$isAuthBtn(['SP_BTN_USER_MODIFY'])"
              type="text"
              size="mini"
              round
              style="margin-left: 10px"
              class="app-color-danger"
              @click="handleUnBindUserWechat(scope.row)"
            >解绑微信
            </el-button>
            <el-button v-if="$isAuthBtn(['SP_BTN_USER_DELETE'])" type="text" size="mini" class="app-color-danger" round @click="handleDelUser(scope.row)">
              删除
            </el-button>
            <!--<el-button type="primary" size="mini" round @click="handleEditUser('edit',scope.row)">编辑</el-button>-->
            <!--<el-button type="primary" size="mini" round @click="handleEditUserPsw(scope.row)">重置密码</el-button>-->
            <!--<el-button :type="scope.row.wechat?'danger':'primary'" size="mini" round @click="handleEditUserStatus(scope.row)">{{ scope.row.wechat?'解绑':'绑定微信' }}</el-button>-->
            <!--<el-button :type="scope.row.status===1?'danger':'primary'" size="mini" round @click="handleEditUserStatus(scope.row)">{{ scope.row.status===1?'停用':'启用' }}</el-button>-->
            <!--<el-button type="danger" size="mini" round @click="handleDelUser(scope.row)">删除</el-button>-->
          </template>
        </el-table-column>
      </el-table>
      <PaginationDirection
        v-if="paginationConfig.total!==0"
        :config="paginationConfig"
        @sizesChange="fetchData"
        @pageChange="fetchData"
      />
    </div>
    <!--list end-->

    <!--组件-->
    <DialogEditOrg ref="dialogEditOrg" />
    <DialogEditUser ref="dialogEditUser" />
    <DialogEditUserPsw ref="dialogEditUserPsw" />
  </div>
</template>

<script>
import DialogEditOrg from './DialogEditOrg'
import DialogEditUser from './DialogEditUser'
import DialogEditUserPsw from './DialogEditUserPsw'
import { mapGetters } from 'vuex'
import { userList, delUser, updateUserStatus } from '@/api/user/index'
import { orgTree, delOrg } from '@/api/user/organization'
import { bindWx, bindWxState, unBindWx } from '@/api/user/auth'

export default {
  components: {
    DialogEditOrg,
    DialogEditUser,
    DialogEditUserPsw
  },
  data() {
    return {
      // 配置
      // 分页配置
      paginationConfig: {
        direction: 'center', // 分页位置
        layout: 'total, sizes, prev, pager, next, jumper', // 分页类型
        pageSizes: [10, 20], // 分页pages
        total: 0,
        page: 1, // 页数-默认1
        pageSize: 10 // 每页条数-默认10
      },
      // 状态
      loading: false,
      bindWechatCodeLoading: false,
      isStopCheckBindWechatState: true,
      // 数据
      bindWechatUserId: null,
      bindWechatCodeNo: null,
      bindWechatQrCodeUrl: null,
      originalTreeList: [],
      treeList: [],
      activeTree: null,
      list: [],
      listFilterForm: {
        name: null,
        orgId: 0
      }
    }
  },
  computed: {
    ...mapGetters(['spInfo', 'userInfo'])
  },
  watch: {},
  beforeCreate() {
  },
  created() {
  },
  beforeMount() {
  },
  mounted() {
    this.fetchData()
  },
  beforeUpdate() {
  },
  update() {
  },
  activated() {
  },
  deactivated() {
  },
  beforeDestroy() {
    this.isStopCheckBindWechatState = true
  },
  destroyed() {
  },
  methods: {
    /**
     * 数据组
     */
    // 初始化
    fetchData() {
      this.loading = true
      Promise.all([this.getTreeList(), this.getUserList()]).then(() => {
        this.loading = false
      })
    },

    // 获取tree
    getTreeList() {
      return new Promise((resolve, reject) => {
        orgTree().then(res => {
          this.originalTreeList = res.data || []
          this.treeList = [
            {
              id: -1,
              name: this.spInfo && this.spInfo.name || '服务商',
              children: res.data || []
            }
          ]
          this.$nextTick(() => {
            this.$refs.treeList.setCurrentKey(this.activeTree && this.activeTree.id || -1)
          })
        }).finally(() => {
          resolve()
        })
      })
    },

    // 获取list
    getUserList() {
      this.loading = true
      return new Promise((resolve, reject) => {
        userList({ data: this.listFilterForm }).then(res => {
          const list = res.data || []
          list.some((v, i) => {
            if (v.id === this.userInfo.id) {
              list.splice(i, 1)
              return true
            }
          })
          this.list = list
        }).finally(() => {
          this.loading = false
          resolve()
        })
      })
    },
    /**
     * 按钮组
     */
    // 新增组织
    handleEditOrg(mode = 'add', node = null, data = null) {
      //  新增根节点
      if (mode === 'add') {
        this.$refs.dialogEditOrg.open({
          mode: 'add',
          parentId: data && data.id || this.activeTree && this.activeTree.id || -1,
          treeList: this.treeList
        }).then(() => {
          this.getTreeList()
        })
      } else if (mode === 'edit' && node && data) {
        this.$refs.dialogEditOrg.open({
          mode: 'edit',
          parentId: null,
          treeList: this.treeList,
          row: data
        }).then(res => {
          this.activeTree.name = res.name
          this.getTreeList()
        })
      }
    },

    // 删除组织
    handleDelOrg(node, data) {
      this.$confirm(
        `确定删除组织：${data.name} ?`,
        '温馨提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          center: true,
          roundButton: true
        }
      )
        .then(() => {
          delOrg({ params: { orgId: data.id } })
            .then(() => {
              if (this.activeTree.id === data.id) this.activeTree = null
              this.$notify({
                title: '成功',
                message: '删除成功',
                type: 'success',
                duration: 2000,
                offset: 40
              })
              this.fetchData()
            })
            .finally(() => {
              this.loading = false
            })
        })
        .catch(() => {
        })
    },

    // 编辑用户
    handleEditUser(mode = 'add', row = null) {
      this.$refs.dialogEditUser.open({
        mode,
        parentId: this.activeTree && this.activeTree.id || -1,
        treeList: this.originalTreeList,
        row
      }).then(() => {
        this.getUserList()
      })
    },

    // 改密
    handleEditUserPsw(row = null) {
      this.$refs.dialogEditUserPsw.open({ row }).then(() => {
      })
    },

    // 绑定微信
    handleBindUserWechat(row) {
      this.bindWechatCodeLoading = true
      this.bindWechatUserId = row.id
      const params = { userId: row.id }
      bindWx({ data: params }).then(res => {
        row.isShowBindWechatPopover = true
        this.bindWechatCodeNo = res.data.codeNo
        this.bindWechatQrCodeUrl = res.data.qrcodeUrl
        this.isStopCheckBindWechatState = false
        this.checkBindWechatState()
      }).finally(() => {
        this.bindWechatCodeLoading = false
      })
    },

    // 查询绑定状态
    checkBindWechatState() {
      if (!this.bindWechatCodeNo) return
      const params = { codeNo: this.bindWechatCodeNo }
      bindWxState({ params })
        .then(res => {
          switch (res.data.state) {
            case 0: {
              const timerId = setTimeout(() => {
                if (this.isStopCheckBindWechatState) return clearTimeout(timerId)
                this.checkBindWechatState()
              }, 2000)
              break
            }
            case 1:
              this.fetchData()
              this.bindWechatPopoverHide()
              this.$alert(`已成功绑定微信：${res.data.nickname}`, '温馨提示', {
                confirmButtonText: '确定',
                center: true,
                type: 'warning',
                roundButton: true,
                callback: action => {
                }
              })
              break
            default :
              this.bindWechatPopoverHide()
              break
          }
        })
        .catch(() => {
          this.bindWechatPopoverHide()
        })
        .finally(() => {
        })
    },

    // 解绑微信
    handleUnBindUserWechat(row) {
      this.$confirm(
        `确定解绑成员【${row.name}】的微信 ?`,
        '温馨提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          center: true,
          roundButton: true
        }
      )
        .then(() => {
          this.loading = true
          const params = { userId: row.id }
          unBindWx({ data: params }).then(() => {
            row.wechat = null
            this.$notify({
              title: '成功',
              message: '解绑成功',
              type: 'success',
              duration: 2000,
              offset: 40
            })
          }).finally(() => {
            this.loading = false
          })
        })
        .catch(() => {
        })
    },

    // 更改用户状态
    handleEditUserStatus(row) {
      this.$confirm(
        `确定${row.status === 1 ? '停用' : '启用'}成员：${row.name} ?`,
        '温馨提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          center: true,
          roundButton: true
        }
      )
        .then(() => {
          const params = { userId: row.id, status: row.status === 1 ? 0 : 1 }
          this.loading = true
          updateUserStatus({ params: params })
            .then(() => {
              this.$notify({
                title: '成功',
                message: row.status === 1 ? '已停用' : '已启用',
                type: 'success',
                duration: 2000,
                offset: 40
              })
              this.fetchData()
            })
            .finally(() => {
              this.loading = false
            })
        })
        .catch(() => {
        })
    },

    // 删除用户
    handleDelUser(row) {
      this.$confirm(
        `确定删除成员：${row.name} ?`,
        '温馨提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          center: true,
          roundButton: true
        }
      )
        .then(() => {
          const params = { userId: row.id }
          this.loading = true
          delUser({ params })
            .then(() => {
              this.$notify({
                title: '成功',
                message: '删除成功',
                type: 'success',
                duration: 2000,
                offset: 40
              })
              this.fetchData()
            })
            .finally(() => {
              this.loading = false
            })
        })
        .catch(() => {
        })
    },

    // 点击tree
    handleTreeClick(data, node) {
      if (node.level === 1) {
        this.activeTree = null
        this.listFilterForm.orgId = null
      } else {
        this.activeTree = data
        this.listFilterForm.orgId = data.id
      }
      this.getUserList()
    },

    // 查询
    submitListFilterForm() {
      this.getUserList()
    },

    // 重置
    resetListFilterForm() {
      this.$refs.listFilterForm.resetFields()
    },

    //
    /**
     * 状态组
     */
    // 二维码隐藏
    bindWechatPopoverHide() {
      this.bindWechatCodeNo = null
      this.bindWechatQrCodeUrl = null
      this.isStopCheckBindWechatState = true
    }
    /**
     * 方法组
     */
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.organization-main {
  display: flex;
  /*reset*/
  ::v-deep .el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content {
    color: $primary;
  }

  /*tree*/
  .tree-container {
    height: calc(100vh - 155px);
    padding-right: 10px;
    text-align: center;
    border-right: 1px solid #EBEEF5;

    ::v-deep .el-tree-node__content {
     padding-right: 10px;
    }

    .custom-tree-node {
      width: 100%;

      .dropdown {
        visibility: hidden;
      }

      &:hover .dropdown {
        visibility: visible;
      }
    }

    .el-icon-more {
      font-size: 18px;
      padding: 5px 10px 10px 10px;
      transform: rotate(90deg);
    }
  }

  /*表格*/
  .table-container {
    overflow: hidden;
    width: 100%;
    padding-left: 10px;

    .table-title {
      margin-bottom: 10px;
      line-height: 40px;
      font-weight: bold;

      .org-name {
        color: $primary;
      }
    }

  }

}

/*绑定微信*/
.wx-qrcode-popover {
  min-height: 250px;

  .qr-code {
    width: 200px;
    height: 200px;
  }
}
</style>
